package org.osomit.sacct.server;

import org.osomit.sacct.remoting.socket.SocketListener;
import org.osomit.sacct.remoting.Listener;
import org.osomit.sacct.account.manager.iface.AccountManager;
import org.osomit.sacct.server.config.iface.ServerConfig;
import org.osomit.sacct.server.wiring.ServerConfigModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;

import java.io.Console;

/**
 * @author Jian Fang (John.Jian.Fang@gmail.com)
 *
 * Date: Jun 27, 2009
 */
public class AccountServer {
    private static String id = "AccountServer";

    public static void main(String[] args)
    {
        int port = 9000;
        int poolSize = 12;

        // Usage
        if(args.length ==0){

        }else if(args.length == 1){
            port = Integer.parseInt(args[0]);
        }else if(args.length == 2){
            // Arguments
            port = Integer.parseInt(args[0]);
            poolSize = Integer.parseInt(args[1]);
        }else{
            System.out.println("USAGE:   " + id + " [port] [thread_pool_size]");
            System.out.println();
            System.out.println("EXAMPLE: " + id + " 9000 12");
            System.out.println();
            System.exit(1);
        }

        String password = null;

        Console con = System.console();
        if (con != null){

//            String uname = con.readLine("Enter your username: ");
            char[] pwd = con.readPassword("Enter account management password: ");
            password = new String(pwd);
            Module configMoudule = new ServerConfigModule();
            Injector injector = Guice.createInjector(configMoudule);

            ServerConfig config = injector.getInstance(ServerConfig.class);
            config.setPoolSize(poolSize);
            config.setServerPort(port);

            AccountManager manager = injector.getInstance(AccountManager.class);

            manager.load(password);

            Listener listener = injector.getInstance(SocketListener.class);
//        SocketListener listener = new SocketListener(port, poolSize);
            listener.setPoolSize(poolSize);
            listener.setPort(port);

            Thread thread = new Thread(listener);
            thread.start();

            AccountServerShutdownHook hook = new AccountServerShutdownHook();
            hook.setListener(listener);
            Runtime.getRuntime().addShutdownHook(hook);
        }else{
            System.out.println("Cannot open soncole");
            System.exit(1);
        }
    }
}
